package top.lyc829.zzl_android.ui.main;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.viewpager.widget.ViewPager;
import androidx.viewpager2.widget.ViewPager2;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import com.next.easynavigation.view.EasyNavigationBar;
import com.xuexiang.xui.utils.StatusBarUtils;
import com.xuexiang.xui.widget.textview.badge.BadgeView;
import com.xuexiang.xupdate.XUpdate;
import com.xuexiang.xutil.app.PathUtils;

import java.util.ArrayList;
import java.util.List;

import top.lyc829.zzl_android.MyApp;
import top.lyc829.zzl_android.R;
import top.lyc829.zzl_android.databinding.ActivityLoginBinding;
import top.lyc829.zzl_android.databinding.ActivityMainBinding;
import top.lyc829.zzl_android.logic.bean.MsgNumberBean;
import top.lyc829.zzl_android.logic.service.MsgNumberService;
import top.lyc829.zzl_android.logic.util.Utils;
import top.lyc829.zzl_android.logic.xupdate.custom.XUpdateServiceParser;
import top.lyc829.zzl_android.ui.BaseActivity;
import top.lyc829.zzl_android.ui.add.AddDynamicActivity;
import top.lyc829.zzl_android.ui.index.IndexFragment;
import top.lyc829.zzl_android.ui.login.LoginActivity;
import top.lyc829.zzl_android.ui.profile.ProfileFragment;
import top.lyc829.zzl_android.ui.profile.ProfileViewModel;
import top.lyc829.zzl_android.ui.team.TeamFragment;
import top.lyc829.zzl_android.ui.thing.ThingFragment;

public class MainActivity extends BaseActivity {

    private ActivityMainBinding binding;

    private EasyNavigationBar navigationBar;
    private String[] tabText = {"首页", "发现", "团队", "我的"};

    private long lastClickBackTime = 0;

    //未选中icon
    private int[] normalIcon = {
            R.drawable.ic_baseline_home_24,
            R.drawable.ic_baseline_thing_24,
            R.drawable.ic_baseline_team_24,
            R.drawable.ic_baseline_profile_24
    };


    //选中时icon
    private int[] selectIcon = {
            R.drawable.ic_baseline_home_24_1,
            R.drawable.ic_baseline_thing_24_1,
            R.drawable.ic_baseline_team_24_1,
            R.drawable.ic_baseline_profile_24_1
    };

    private List<Fragment> fragments = new ArrayList<>();
    private Handler mHandler = new Handler();
    private boolean flag = true;

    private MainViewModel mViewModel;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setContentView(binding.getRoot());

        mViewModel = new ViewModelProvider(this).get(MainViewModel.class);

        //navigateTo(LoginActivity.class);


//        NavController controller = Navigation.findNavController(this, R.id.fragment);
//        AppBarConfiguration configuration = new AppBarConfiguration.Builder(binding.bottomNavigationView.getMenu()).build();
//        NavigationUI.setupActionBarWithNavController(this, controller, configuration);
//        NavigationUI.setupWithNavController(binding.bottomNavigationView, controller);


        navigationBar = findViewById(R.id.navigationBar);

        fragments.add(IndexFragment.newInstance());
        fragments.add(ThingFragment.newInstance());
        fragments.add(TeamFragment.newInstance());
        fragments.add(ProfileFragment.newInstance());

        ViewPager2 viewPager2 = findViewById(R.id.main_viewpager2);
        viewPager2.setAdapter(new ViewPager2Adapter(this, fragments));
        viewPager2.setUserInputEnabled(false);  // 禁止滑动
        viewPager2.setOffscreenPageLimit(fragments.size());
        // viewpager2默认不加载当前fragment两侧的fragment，所以不需要额外设置懒加载
        // 但是，viewpager2有缓存机制，缓存3个页面，打开第四个页面时，第三个页面会被清理。
        // 如果需要达到不清理的效果，需要设置setOffscreenPageLimit()，这样又预加载了，需要实现懒加载。
        // viewpager2中只有可见的fragment才执行onResume方法，所以在onResume中判断即可

        navigationBar
                .defaultSetting()
                .titleItems(tabText)
                .normalIconItems(normalIcon)
                .selectIconItems(selectIcon)
                .centerImageRes(R.drawable.ic_baseline_add_48_1)
                .centerLayoutRule(EasyNavigationBar.RULE_BOTTOM)
                .centerTextStr("")
                .centerLayoutBottomMargin(0)
                .centerAlignBottom(true)
                .setOnCenterTabClickListener(view -> {
                    Intent intent = null;
                    if (!Utils.isLogin()) {
                        Utils.showToast("请先登录");
                        intent = new Intent(this, LoginActivity.class);
                    } else {
                        intent = new Intent(this, AddDynamicActivity.class);
                    }
                    startActivity(intent);
                    return false;
                })
                .mode(EasyNavigationBar.NavigationMode.MODE_ADD)
                .hasPadding(true)
                .setupWithViewPager(viewPager2)
                .build();

        msgNumberService();

        update();

    }


    private void update() {
        XUpdate.newBuild(this)
                .apkCacheDir(PathUtils.getExtDownloadsPath())
                .updateHttpService(XUpdateServiceParser.getUpdateHttpService())
                .isGet(false)
                .updateUrl(XUpdateServiceParser.getVersionCheckUrl())
                .updateParser(new XUpdateServiceParser())
                .update();

        //EasyUpdate.checkUpdate(this, "http://lyc829.top:1111/update/checkVersion");
    }

    /**
     * 处理获取消息个数的服务
     */
    private void msgNumberService() {
//        Intent intent = new Intent(this, MsgNumberService.class);
//        ServiceConnection connection = new ServiceConnection() {
//            @Override
//            public void onServiceConnected(ComponentName name, IBinder service) {
//                MsgNumberService.MyBinder myService = (MsgNumberService.MyBinder) service;
//                myService.getService().getMsgNumberLiveData().observe(MainActivity.this, msgNumberBean -> {
//                    mViewModel.getMsgNumberLiveData().setValue(msgNumberBean);
//                });
//            }
//
//            @Override
//            public void onServiceDisconnected(ComponentName name) {
//
//            }
//        };
//        startService(intent);
//        bindService(intent, connection, Context.BIND_AUTO_CREATE);
    }


    @Override
    protected void onResume() {
        super.onResume();
        mViewModel.updateMsgNumber();
    }

    @Override
    public void onBackPressed() {
        exit();
    }

    /**
     * 实现按两次返回键退出
     */
    private void exit() {
        long currentTime = System.currentTimeMillis();
        if (currentTime - lastClickBackTime > 2000) {
            lastClickBackTime = currentTime;
            Utils.showToast("再按一次退出");
            return;
        }
        finish();
    }
}